package com.zhq.blog.manage.domain.controller.money;

import javax.validation.Valid;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhq.blog.core.domain.money.Card;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/money/card/*")
public class CardController extends BaseController {
	
	@RequestMapping()
    public BossModel index(){
		return createModel("admin/money/card/list").add("cardPage",context.getCardRepository().findAll());
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("admin/money/card/info").add("card",context.getCardRepository().findOne(id));
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createCardModel(new Card());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final Card card, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectCard,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if (bindingResult.hasErrors()) {
			return createModel("admin/money/card/info");
		}
		context.getCardRepository().save(card);
		String message = card.getSucessFlashMessage();
		redirectCard.addFlashAttribute("message", message);
		return createModel("redirect:/admin/money/card/index");
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id){
		context.getCardRepository().delete(id);
		return createModel("admin/money/card/card_table").add("cardPage",context.getCardRepository().findAll());
	}
	
	private BossModel createCardModel(Card card){
		BossModel modelAndView = createModel("admin/money/card/info");
		if(card != null)
			modelAndView.add("card",card);
		return modelAndView;
	}

}
